package org.footballmanager.pandafootball.common.configure;

import org.footballmanager.pandafootball.common.converter.UniversalEnumConverterFactory;
import org.footballmanager.pandafootball.common.intercepter.MyInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * 配置Web
 * @author chenjian
 * @since 2017年10月18日下午5:17:22
 */
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurationSupport {
    /**
     * 配置静态访问资源
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/js/**").addResourceLocations("classpath:/static/js/");
        registry.addResourceHandler("/css/**").addResourceLocations("classpath:/static/css/");
        registry.addResourceHandler("/font/**").addResourceLocations("classpath:/static/font/");
        registry.addResourceHandler("/icons/**").addResourceLocations("classpath:/static/icons/");
        registry.addResourceHandler("/images/**").addResourceLocations("classpath:/static/images/", "classpath:/images/");
        super.addResourceHandlers(registry);
    }

	/**
	 * 增加枚举转换工厂
	 * @param registry 参数
	 */
	@Override
	public void addFormatters(FormatterRegistry registry) {
		registry.addConverterFactory(new UniversalEnumConverterFactory());
	}

	@Override
    public void addViewControllers(ViewControllerRegistry registry){
	    //设置首页默认打开页面或action
        registry.addViewController("/").setViewName("index.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);
    }
	
	/**
	 * 此方法把该拦截器实例化成一个bean,否则在拦截器里无法注入其它bean
	 * @return 拦截器
	 */
	@Bean
	MyInterceptor myInterceptor() {
		return new MyInterceptor();
	}

	/**
	 * 把拦截器注册到spring
	 * @param registry 参数
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		// 多个拦截器组成一个拦截器链
		// addPathPatterns 用于添加拦截规则
		// excludePathPatterns 用户排除拦截
		registry.addInterceptor(myInterceptor())
		.addPathPatterns("/**")
		.excludePathPatterns("/", "/css/**", "/js/**", "/font/**", "/icons/**", "/images/**",
                "/regist", "/addmore", "/login", "/getcookie", "/forgetpwd", "/forgetpwd2", "/verifyCode");
		super.addInterceptors(registry);
	}

}
